package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.gulimall.search.config.ElasticsearchConfig;
import com.atguigu.gulimall.search.constant.EsConstants;
import com.atguigu.gulimall.search.service.ProductSaveService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    RestHighLevelClient restHighLevelClient;

    public Boolean productStatusUp(List<SkuEsModel> skuList) throws IOException {

        //1、建立索引。product，建立好映射关系
        //2、保存es数据
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel sku : skuList) {
            IndexRequest indexRequest = new IndexRequest(EsConstants.PRODUCT_INDEX);
            indexRequest.id(sku.getSkuId().toString());
            String s = JSON.toJSONString(sku);
            indexRequest.source(s, XContentType.JSON);

            bulkRequest.add(indexRequest);
        }
        boolean b = false;
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ElasticsearchConfig.COMMON_OPTIONS);
        b = bulk.hasFailures();
        Arrays.asList(bulk.getItems()).stream().map(sku->{
            return sku.getId();
        }).collect(Collectors.toList());
        return b;
    }
}
